package com.small.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json操作工具类
 * Created by fangzheng on 2018/1/30.
 */
public final class JsonUtils {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 将pojo转换为json字符串
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String toJson(T obj){
        String json = null;
        try {
            json = OBJECT_MAPPER.writeValueAsString(obj);
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 将json转换为pojo
     * @param json
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String json,Class<T> type){
        T pojo = null;
        try {
            pojo = OBJECT_MAPPER.readValue(json,type);
        }catch (Exception e){
            e.printStackTrace();
        }
        return pojo;
    }

}
